#!/usr/bin/env python3
"""
一键添加新过滤器工具
只需要提供基本信息，自动完成所有相关代码的更新
"""

import sys
import os
from pathlib import Path

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

def add_new_filter():
    """交互式添加新过滤器"""
    
    print("🎯 添加新过滤器向导")
    print("=" * 50)
    
    # 收集基本信息
    key = input("过滤器key (如: entry_reasons): ").strip()
    label = input("显示标签 (如: 入场原因): ").strip()
    db_field = input("数据库字段名 (如: entry_reason): ").strip()
    description = input("描述 (如: 选择入场原因): ").strip()
    
    # 选择过滤器类型
    print("\n🎨 选择过滤器类型:")
    print("1. 多选下拉框 (MULTI_SELECT) - 如品种、方向等")
    print("2. 单选下拉框 (SINGLE_SELECT) - 如状态选择")
    print("3. 数字范围 (RANGE) - 如盈亏金额、交易数量")
    print("4. 单个数字 (NUMBER) - 如当日第几笔")
    print("5. 文本输入 (TEXT) - 如备注搜索")
    print("6. 布尔选择 (BOOLEAN) - 如是否盈利")
    
    type_choice = input("请选择类型 (1-6): ").strip()
    
    filter_types = {
        "1": "FilterType.MULTI_SELECT",
        "2": "FilterType.SINGLE_SELECT", 
        "3": "FilterType.RANGE",
        "4": "FilterType.NUMBER",
        "5": "FilterType.TEXT",
        "6": "FilterType.BOOLEAN"
    }
    
    if type_choice not in filter_types:
        print("❌ 无效选择")
        return
    
    filter_type = filter_types[type_choice]
    
    # 根据类型收集不同的配置
    options = []
    additional_config = {}
    
    if type_choice in ["1", "2"]:  # 选择类型
        print(f"\n请输入选项列表 (每行一个，空行结束):")
        while True:
            option = input(f"选项 {len(options) + 1}: ").strip()
            if not option:
                break
            options.append(option)
        
        if not options:
            print("❌ 至少需要一个选项")
            return
            
    elif type_choice == "3":  # 数字范围
        min_val = input("最小值 (可选，回车跳过): ").strip()
        max_val = input("最大值 (可选，回车跳过): ").strip()
        step = input("步长 (默认1): ").strip() or "1"
        
        if min_val:
            additional_config["min_value"] = float(min_val)
        if max_val:
            additional_config["max_value"] = float(max_val)
        additional_config["step"] = float(step)
        
    elif type_choice == "4":  # 单个数字
        min_val = input("最小值 (可选，回车跳过): ").strip()
        max_val = input("最大值 (可选，回车跳过): ").strip()
        step = input("步长 (默认1): ").strip() or "1"
        
        if min_val:
            additional_config["min_value"] = float(min_val)
        if max_val:
            additional_config["max_value"] = float(max_val)
        additional_config["step"] = float(step)
        
    elif type_choice == "5":  # 文本输入
        case_sensitive = input("是否区分大小写? (y/n, 默认n): ").strip().lower()
        additional_config["case_sensitive"] = case_sensitive == "y"
        
    elif type_choice == "6":  # 布尔选择
        true_label = input("True选项标签 (默认'是'): ").strip() or "是"
        false_label = input("False选项标签 (默认'否'): ").strip() or "否"
        options = [true_label, false_label]
    
    # 生成配置代码
    config_parts = [
        f'        key="{key}",',
        f'        label="{label}",',
        f'        filter_type={filter_type},',
        f'        db_field="{db_field}",',
    ]
    
    if options:
        config_parts.append(f'        options={options},')
    
    for key_name, value in additional_config.items():
        if isinstance(value, str):
            config_parts.append(f'        {key_name}="{value}",')
        else:
            config_parts.append(f'        {key_name}={value},')
    
    config_parts.append(f'        description="{description}"')
    
    config_code = f'''
    FilterConfig(
{chr(10).join(config_parts)}
    ),'''
    
    print("\n🚀 生成的配置代码:")
    print("=" * 50)
    print(config_code)
    print("=" * 50)
    
    # 询问是否自动添加
    if input("\n是否自动添加到配置文件? (y/n): ").lower() == 'y':
        add_to_config_file(config_code)
        print("✅ 已添加到配置文件")
        
        # 询问是否生成代码
        if input("是否立即生成相关代码? (y/n): ").lower() == 'y':
            from tools.filter_generator import FilterCodeGenerator
            generator = FilterCodeGenerator()
            generator.generate_all_code()
    
    print("\n📋 手动步骤:")
    print("1. 确保数据库模型包含字段:", db_field)
    print("2. 更新Mock数据生成器以包含新字段")
    print("3. 运行测试并更新预期结果")

def add_to_config_file(config_code):
    """将新配置添加到配置文件"""
    config_file = project_root / "config" / "filter_config.py"
    
    with open(config_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 找到FILTER_CONFIGS列表的开始和结束位置
    start_pos = content.find('FILTER_CONFIGS = [')
    if start_pos == -1:
        print("❌ 找不到FILTER_CONFIGS列表")
        return
    
    # 从FILTER_CONFIGS开始位置查找对应的结束括号
    bracket_count = 0
    pos = start_pos + len('FILTER_CONFIGS = [')
    while pos < len(content):
        if content[pos] == '[':
            bracket_count += 1
        elif content[pos] == ']':
            if bracket_count == 0:
                # 找到了FILTER_CONFIGS的结束位置
                insert_pos = pos
                break
            bracket_count -= 1
        pos += 1
    else:
        print("❌ 找不到FILTER_CONFIGS列表的结束位置")
        return
    
    # 插入新配置
    new_content = content[:insert_pos] + config_code + '\n' + content[insert_pos:]
    
    with open(config_file, 'w', encoding='utf-8') as f:
        f.write(new_content)

def show_existing_filters():
    """显示现有过滤器"""
    try:
        from config.filter_config import FILTER_CONFIGS
        print("\n📋 现有过滤器:")
        print("=" * 50)
        for i, config in enumerate(FILTER_CONFIGS, 1):
            print(f"{i}. {config.key} ({config.label}) - {config.description}")
            print(f"   字段: {config.db_field}, 选项: {config.options}")
        print("=" * 50)
    except ImportError:
        print("❌ 无法加载配置文件")

def main():
    """主函数"""
    while True:
        print("\n🔧 过滤器管理工具")
        print("=" * 50)
        print("1. 添加新过滤器")
        print("2. 查看现有过滤器")
        print("3. 生成所有代码")
        print("0. 退出")
        print("=" * 50)
        
        choice = input("请选择操作 (0-3): ").strip()
        
        if choice == "1":
            add_new_filter()
        elif choice == "2":
            show_existing_filters()
        elif choice == "3":
            from tools.filter_generator import FilterCodeGenerator
            generator = FilterCodeGenerator()
            generator.generate_all_code()
        elif choice == "0":
            print("👋 再见!")
            break
        else:
            print("❌ 无效选择")

if __name__ == "__main__":
    main() 